package it.infodea.tapestrydea.pages.demodea;

import it.infodea.tapestrydea.entities.demo.UserBean;
import it.infodea.tapestrydea.services.breadcrumb.BreadcrumbService;
import it.infodea.tapestrydea.support.DeaEventConstants;
import it.infodea.tapestrydea.support.DeaUtils;
import it.infodea.tapestrydea.support.annotations.PageInfo;
import it.infodea.tapestrydea.support.enumerations.SecurityGroup;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

@PageInfo(category = "demo", allowedSecurityGroup=SecurityGroup.ANONYMOUS, mode = PageInfo.MODE_NORMAL)
public class CrudDemoDea {

	@Inject
	private ComponentResources resources;

	@Inject
	private BreadcrumbService breadcrumbService;

	@Persist
	private List<UserBean> users;

	@SetupRender
	void setup() {
		breadcrumbService.addBreadcrumb(resources);
		if (users == null) {
			users = new ArrayList<UserBean>();
			for (int i = 0; i < 3; i++) {
				users.add(newUser(i));
			}
		}
	}

	@OnEvent(DeaEventConstants.CONFIRM)
	void onDelete(UserBean user) {
		for (UserBean u : users) {
			if (u.getIdValue().equals(user.getIdValue())) {
				users.remove(u);
				return;
			}
		}
	}

	@OnEvent(DeaEventConstants.SAVE)
	void onSave(UserBean user) {
		if (DeaUtils.isEmpty(user)) {
			onCreate(user);
		} else {
			onUpdate(user);
		}
	}

	private void onCreate(UserBean user) {
		long id = getMaxUsersId() + 1l;
		user.setId(id);
		users.add(user);
	}

	private void onUpdate(UserBean user) {
		for (UserBean u : users) {
			if (u.getIdValue().equals(user.getIdValue())) {
				u.setFirstName(user.getFirstName());
				u.setLastName(user.getLastName());
				u.setAge(user.getAge());
				return;
			}
		}
	}

	private long getMaxUsersId() {
		long id = -1l;
		for (UserBean u : users) {
			if (id < u.getId()) {
				id = u.getId();
			}
		}
		return id;
	}

	private UserBean newUser(int i) {
		return UserBean.newInstance("FirstName_" + i, "LastName_" + i, i, i);
	}

	public List<UserBean> getUsers() {
		return users;
	}

	public Class<UserBean> getUserClass() {
		return UserBean.class;
	}
}
